package com.kool.kadmin.common.context;

import java.util.HashMap;
import java.util.Map;

/**
 * 请求上下文
 *
 * @author luyu
 */
public class ReqContext {
    public static final String USER_ID = "userId";
    public static final String USER_NAME = "userName";
    public static final String TOKEN = "token";
    public static final String APPID = "appid";
    /**
     * 本地线程变量，请求间信息隔离，父子线程间共享请求信息
     */
    private static final ThreadLocal<Map<String, Object>> local = new InheritableThreadLocal<>();

    public static Map<String, Object> getContext() {
        Map map = local.get();
        if (map == null) {
            map = new HashMap();
            local.set(map);
        }
        return map;
    }

    /**
     * 取上下文信息
     *
     * @param key
     * @return
     */
    public static Object get(String key) {
        return getContext().get(key);
    }

    /**
     * 放入登录用户id和用户姓名
     *
     * @param userId
     * @param userName
     */
    public static void setUser(Long userId, String userName) {
        Map map = getContext();
        map.put(USER_ID, userId);
        map.put(USER_NAME, userName);

    }

    /**
     * 取用户id
     *
     * @return
     */
    public static Long getUserId() {
        return (Long) getContext().get(USER_ID);
    }

    /**
     * 取用户姓名
     *
     * @return
     */
    public static String getUserName() {
        return (String) getContext().get(USER_NAME);
    }

    /**
     * 放token
     *
     * @param token
     */
    public static void setToken(String token) {
        getContext().put(TOKEN, token);
    }

    /**
     * 取token
     *
     * @return
     */
    public static String getToken() {
        return (String) getContext().get(TOKEN);
    }

    /**
     * 放appid
     *
     * @param appid
     */
    public static void setAppid(String appid) {
        getContext().put(APPID, appid);
    }

    /**
     * 取appid
     *
     * @return
     */
    public static String getAppid() {
        return (String) getContext().get(APPID);
    }
}
